package com.kcloud.commons.authorization.settings.biz.service.impl;

import com.kcloud.commons.authorization.AuthorizationCacheHolder;
import com.kcloud.commons.authorization.AuthorizationConfig;
import com.kcloud.commons.authorization.annotation.AuthorizationAttr;
import com.kcloud.commons.authorization.annotation.AuthorizationGroup;
import com.kcloud.commons.authorization.settings.biz.dao.BizEntityRepository;
import com.kcloud.commons.authorization.settings.biz.dao.BizFunctionRepository;
import com.kcloud.commons.authorization.settings.biz.dao.UserBizFunctionRepository;
import com.kcloud.commons.authorization.settings.biz.entity.BizEntity;
import com.kcloud.commons.authorization.settings.biz.entity.BizFunction;
import com.kcloud.commons.authorization.settings.biz.entity.CtrlUnitBizFunction;
import com.kcloud.commons.authorization.settings.biz.entity.UserBizFunction;
import com.kcloud.commons.authorization.settings.biz.service.BizSettingsService;

import com.kcloud.commons.entity.control.Attribute;
import com.kcloud.commons.entity.control.AttributeGroup;
import com.kcloud.commons.entity.control.BizDomain;
import com.kcloud.jpa.conditions.query.DefaultQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 默认业务设置接口实现
 *
 * @author songhuiqing
 */
@Service
public class DefaultBizSettingsServiceImpl implements BizSettingsService {

    @Autowired
    private AuthorizationConfig authorizationConfig;

    @Autowired
    private BizEntityRepository bizEntityRepository;

    @Autowired
    private BizFunctionRepository bizFunctionRepository;

    @Autowired
    private UserBizFunctionRepository userBizFunctionRepository;


    @Override
    public BizDomain getBizDomain(BizDomain domain) {
        List<AttributeGroup> groups = new ArrayList<>();
        AuthorizationGroup authGrp = domain.getCls().getDeclaredAnnotation(AuthorizationGroup.class);
        AttributeGroup mainGrp = new AttributeGroup(authGrp.code(), authGrp.name(), authGrp.type());
        groups.add(mainGrp);
        Field[] fields = domain.getCls().getFields();
        Arrays.stream(fields).forEach(f -> {
            //TODO 初始化默认domains，将基准功能和属性中的操作，单独设置接口抛出去，是否可以维护呢，想不好
            AuthorizationAttr attrAnno = f.getDeclaredAnnotation(AuthorizationAttr.class);
            if(AuthorizationAttr.class.equals(attrAnno.alias())) {
                mainGrp.addAttribute(new Attribute(attrAnno.code(), attrAnno.name(),attrAnno.primaryKey(),attrAnno.foreignKey()));
            } else {
                //TODO 子集处理
            }

        });
        domain.setAttributeGroups(groups);
        return domain;
    }

    @Override
    public void addBizEntity(BizEntity entity) {
        bizEntityRepository.insert(entity);
    }

    @Override
    public void updateBizEntity(BizEntity entity) {
        bizEntityRepository.updateById(entity);
    }

    @Override
    public void deleteBizEntity(String[] ids) {
        DefaultQueryWrapper wrapper = new DefaultQueryWrapper();
        wrapper.in("biz_entity_id", ids);
        bizEntityRepository.delete(wrapper);
    }

    @Override
    public List<BizEntity> listBizEntity() {
        return bizEntityRepository.selectList(null);
    }

    @Override
    public BizEntity getBizEntity(String id) {
        return bizEntityRepository.selectById(id);
    }

    @Override
    public void addBizFunction(BizFunction function) {
        bizFunctionRepository.insert(function);
    }

    @Override
    public void deleteBizFunction(String[] ids) {
        DefaultQueryWrapper wrapper = new DefaultQueryWrapper();
        wrapper.in("config_id", ids);
        bizFunctionRepository.delete(wrapper);
    }

    @Override
    public List<BizFunction> listBizFunction(String bizEntityId) {
        DefaultQueryWrapper wrapper = new DefaultQueryWrapper();
        wrapper.eq("biz_entity_id", bizEntityId);
        return bizFunctionRepository.selectList(wrapper);
    }

    public List<BizFunction> listBizFunction(String[] bizFunctionIds){
        DefaultQueryWrapper wrapper = new DefaultQueryWrapper();
        wrapper.in("config_id", bizFunctionIds);
        return bizFunctionRepository.selectList(wrapper);
    }

    @Override
    public void updateBizFunction(BizFunction function) {
        bizFunctionRepository.updateById(function);
    }

    @Override
    public BizFunction getBizFunction(String id) {
        return bizFunctionRepository.selectById(id);
    }

    @Override
    public void addBizFunctionToUser(CtrlUnitBizFunction ctrlUnitBizFunction) {
        ctrlUnitBizFunction.getCtrlUnits().forEach(ctrlUnit -> {
            ctrlUnitBizFunction.getBizFunctions().stream().map(bf -> new UserBizFunction(ctrlUnit, bf)).forEach(uf -> userBizFunctionRepository.insert(uf));
        });
    }

    @Override
    public UserBizFunction getUserBizFunction(String userId, String funcCode) {
        return AuthorizationCacheHolder.getUserBizFunction(userId, funcCode);
    }


    @Override
    public List<UserBizFunction> listUserBizFunction(String userId, String configId) {
        DefaultQueryWrapper wrapper = new DefaultQueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.eq("config_id", configId);
        return userBizFunctionRepository.selectList(wrapper);
    }
}
